package com.nexus.plugin.redis.lock;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * Redis锁切面处理
 *
 * @Date 2025/9/13 00:43
 * @Author luzhengning
 **/
@Aspect
@Component
@Slf4j
public class RedisLockAspect {

    @Autowired
    private RedisLockService redisLockService;

    @Around("@annotation(redisLock)")
    public Object around(ProceedingJoinPoint joinPoint, RedisLock redisLock) throws Throwable {
        // 生成锁的key
        String lockKey = redisLockService.generateLockKey(redisLock, joinPoint);

        // 使用分布式锁执行方法
        return redisLockService.executeWithLock(
                lockKey,
                redisLock.waitTime(),
                redisLock.leaseTime(),
                redisLock.timeUnit(),
                () -> {
                    try {
                        return joinPoint.proceed();
                    } catch (Throwable e) {
                        if (e instanceof RuntimeException) {
                            throw (RuntimeException) e;
                        }
                        throw new RuntimeException(e);
                    }
                }
        );
    }

}
